package com.haoran.dwz.config.util;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.MapPropertySource;

import com.google.common.base.Optional;
import com.netflix.config.PollResult;
import com.netflix.config.PolledConfigurationSource;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;

public class ConsulConfigurationSource extends MapPropertySource implements PolledConfigurationSource  {

	public ConsulConfigurationSource(String name, Map<String, Object> source) {
		super(name, source);
		this.keyName = name;
	}

	private String keyName;

	public ConsulConfigurationSource(String keyName) {
		this(keyName,null);
	}

	@Override
	public PollResult poll(boolean arg0, Object arg1) throws Exception {
		KeyValueClient kvClient = Consul.newClient().keyValueClient();
		Optional<String> kvOpt = kvClient.getValueAsString(keyName);
		String kvStr = StringUtils.EMPTY;
		if (kvOpt.isPresent()) {
			kvStr = kvOpt.get();
		}
		Properties props = new Properties();
		props.load(new StringReader(kvStr));
		Map<String, Object> complete = new HashMap<>();
		for (Object key : props.keySet()) {
			complete.put((String) key, props.get(key));
		}
		getSource().putAll(complete);
		return PollResult.createFull(complete);
	}

}
